﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zo.Http;
using Zo.Jwt;
using Zo.Models;
using ZoLone.Models;
using ZoLone.Models.Sys;

namespace ZoLone.Logics.Sys
{
    public class AccountLogic:BaseLogic
    {
        public string Checked(string uName, string uPwd, string loginCode="")
        {
            if (string.IsNullOrEmpty(uName))
                throw new ErrorBox("Please enter one user name!");
            if (string.IsNullOrEmpty(uPwd))
                throw new ErrorBox("Please input a password!");
            //if (string.IsNullOrEmpty(loginCode))
            //    throw new ErrorBox("请输入验证码");
            var admin = db.Sys_Admin.Where(c => c.Name.Equals(uName)).FirstOrDefault();


            if (admin == null)
            {
                throw new ErrorBox("User does not exist!");
            }

            if (admin.Password.Trim().ToString() != uPwd)
            {
                throw new ErrorBox("Password error!");
            }

            //string code = Tools.GetCookie("loginCode");
            //if (string.IsNullOrEmpty(code))
            //    throw new ErrorBox("验证码失效");
            //if (!code.ToLower().Equals(loginCode.ToLower()))
            //    throw new ErrorBox("验证码不正确");

            return new JwtManager().GetToken(admin.Id.ToString());
        }

        /// <summary>
        /// 获取 账户信息
        /// </summary>
        /// <returns></returns>
        public Account Get()
        {
            var token = HttpCookieHelper.GetCookie("Authorization");

            var Uid = new JwtManager().ReadJwtToken(token);
            int u = Convert.ToInt32(Uid);
            Sys_Admin admin = this.db.Sys_Admin.Where(c => c.Id.Equals(u)).SingleOrDefault();
            return this.GetAccountByUser(admin);
        }

        public Account GetAccountByUser(Sys_Admin admin)
        {
            if (admin==null)
            {
                return null;
            }
            Account account = new Account();
            var RoleList = this.db.Sys_AdminRole.Where(c => c.AdminId.Equals(admin.Id)).ToList();
            account.RoleIdList = RoleList.Select(c => c.RoleId).ToList();
            account.Nickname = admin.Nickname;
            account.UserId = admin.Id;
            account.UserName = admin.Name;
            account.Admin = admin;
            account.AdminId = admin.Id;
            account.IsSuperAdmin = RoleList.Any(c => c.RoleId == 1);//默认超级管理员的id=1
            return account;
        }
    }
}
